package com.example.allshengmedical.experimentrun.activity;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

public class MyLog {
	private static String TAG = "LogToFile";

	private static String logPath = Environment.getExternalStorageDirectory()
			+ "/" + "AllShengLog";// log日志存放路径

	private static SimpleDateFormat dateFormat = new SimpleDateFormat(
			"yyyy-MM-dd_HH-mm-ss", Locale.US);// 日期格式;

	private static Date date = new Date();

	static int i = 0;

	public static void e(String s1, final String s) {
		Thread thread = new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				writeToFile(s);
			}
		});
		thread.start();

	}

	public static void writeToFile(String msg) {

		// FileInputStream fis = null;
		FileOutputStream fos = null;// FileOutputStream会自动调用底层的close()方法，不用关闭
		if (null == logPath) {
			Log.e(TAG, "logPath == null ，未初始化LogToFile");
			return;
		}
		String fileName = logPath + "/" + "超时log_"
				+ dateFormat.format(System.currentTimeMillis()) + msg + ".log";
		String log = dateFormat.format(date) + " " + "error" + " " + "" + " "
				+ msg + "\n";// log日志内容，可以自行定制

		// 如果父路径不存在
		File file = new File(logPath);
		if (!file.exists()) {
			file.mkdirs();// 创建父路径
		}

		BufferedWriter bw = null;
		try {

			fos = new FileOutputStream(fileName, true);// 这里的第二个参数代表追加还是覆盖，true为追加，flase为覆盖
			bw = new BufferedWriter(new OutputStreamWriter(fos));
			bw.write(log);

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (bw != null) {
					fos.close();
					bw.close();
					bw.close();// 关闭缓冲流
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}
}